from flask import g, jsonify, Blueprint
from flask_restful import Resource, reqparse, fields, abort, marshal, Api

from apps.models.moey_model import WalletMoney
from apps.models.user_model import User
from apps.utils.decorator import login_required
from exts import db

'''
验证是否登陆
    输入兑换B数量
    输入收币地址
    检测是否A数量足够兑换

'''
duihuan_bp = Blueprint('duihuan', __name__, url_prefix='/duihuan')

api = Api(duihuan_bp)


parser = reqparse.RequestParser()
parser.add_argument('money_localtion', type=str, required=True, help='必须输入收币地址')
parser.add_argument('moneyA_count', type=float, required=True, help='必须输入要兑换的数量')

duihuan_fileds = {
    # 货币A
    'moneyA': fields.Float,
    # 货币B
    'moneyB': fields.Float,
}


class DuiHuanResourse(Resource):
    @login_required
    def post(self):
        user = g.user
        if user:
            # 20A=1B
            args = parser.parse_args()
            di_zhi = args.get("money_localtion")
            moneyA_count = args.get("moneyA_count")
            if not di_zhi:
                abort(400, msg='请输入收币地址')
            print(moneyA_count)
            money = WalletMoney.query.filter(WalletMoney.money_localtion == di_zhi).first()
            if money:
                moneyB = money.moneyB
                if moneyA_count // 20 > moneyB:
                    abort(401, msg='货币B不足兑换,请充值')
                else:
                    money.moneyA += moneyA_count
                    money.moneyB -= moneyA_count // 20
                    db.session.add(money)
                    db.session.commit()

                    data = {
                        'status': 200,
                        'msg': '兑换成功',
                        'money': marshal(money, duihuan_fileds)
                    }
                    return jsonify(data)
            else:
                abort(400, msg='地址输入有误')


api.add_resource(DuiHuanResourse, '/')

